package com.openlogic.common.logic.utils.rpc;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
* @ClassName: OkHttpUtils
* @Description: OKHttp3远程访问接口通用工具类
* @author weiyongpeng
* @date 2024年8月6日 上午8:54:07
 */
public class OkHttpUtils {

    private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);

    private static final String HTTP_JSON = "application/json; charset=utf-8";
    private static final String HTTP_FORM = "application/x-www-form-urlencoded; charset=utf-8";

    /**
     * 超时设置
     */
    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(120, TimeUnit.SECONDS)	// 连接超时2min
            .readTimeout(120, TimeUnit.SECONDS)  	// 请求超时2min
            .writeTimeout(120, TimeUnit.SECONDS) 	// 响应超时2min
            .build();

    /**
    * 描述：get请求 说明：对于小文档，响应体上的string()方法非常方便和高效，但是，如果响应主体很大(大于1 MB)，则应避免string()，
    * 因为它会将整个文档加载到内存中。在这种情况下，将主体处理为流。
    * @Title: httpGet
    * @param url
    * @return
    * @author weiyongpeng
    * @date  2024年8月6日 上午8:54:45
     */
    public static String httpGet(String url) {
        if (url == null || "".equals(url)) {
            log.error("url为null!");
            return "";
        }

        Request.Builder builder = new Request.Builder();
        Request request = builder.get().url(url).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.code() == 200) {
                log.info("http GET 请求成功; [url={}]", url);
                return response.body().string();
            } else {
                log.warn("Http GET 请求失败; [errorCode = {} , url={}]", response.code(), url);
            }
        } catch (IOException e) {
            throw new RuntimeException("同步http GET 请求失败,url:" + url, e);
        }
        return null;
    }

    /**
    * 描述：带header的get请求 header非必填
    * @Title: httpGet
    * @param url
    * @param headers
    * @return
    * @author weiyongpeng
    * @date  2024年8月6日 上午8:56:37
     */
    public static String httpGet(String url, Map<String, String> headers) {
        if (headers != null && !headers.isEmpty()) {
            return httpGet(url);
        }

        Request.Builder builder = new Request.Builder();
        headers.forEach((String key, String value) -> builder.header(key, value));
        Request request = builder.get().url(url).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.code() == 200) {
                log.info("http GET 请求成功; [url={}]", url);
                return response.body().string();
            } else {
                log.warn("Http GET 请求失败; [errorxxCode = {} , url={}]", response.code(), url);
            }
        } catch (IOException e) {
            throw new RuntimeException("同步http GET 请求失败,url:" + url, e);
        }
        return null;
    }

    /**
    * 描述：同步 POST调用 无Header
    * @Title: httpPostJson
    * @param url
    * @param json
    * @return
    * @author weiyongpeng
    * @date  2024年8月6日 上午8:57:20
     */
    public static String httpPostJson(String url, String json) {
        if (url == null || "".equals(url)) {
            log.error("url为null!");
            return "";
        }

        MediaType JSON = MediaType.parse(HTTP_JSON);
        @SuppressWarnings("deprecation")
		RequestBody body = RequestBody.create(JSON, json);
        Request.Builder requestBuilder = new Request.Builder().url(url);
        Request request = requestBuilder.post(body).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.code() == 200) {
                log.info("http Post 请求成功; [url={}, requestContent={}]", url, json);
                return response.body().string();
            } else {
                log.warn("Http POST 请求失败; [ errorCode = {}, url={}, param={}]", response.code(), url, json);
            }
        } catch (IOException e) {
            throw new RuntimeException("同步http请求失败,url:" + url, e);
        }
        return null;
    }

    /**
    * 描述：同步 POST调用 有Header
    * @Title: httpPostJson
    * @param url
    * @param headers
    * @param json
    * @return
    * @author weiyongpeng
    * @date  2024年8月6日 上午8:57:42
     */
    public static String httpPostJson(String url, Map<String, String> headers, String json) {
        if (headers != null && !headers.isEmpty()) {
            httpPostJson(url, json);
        }

        MediaType JSON = MediaType.parse(HTTP_JSON);
        @SuppressWarnings("deprecation")
		RequestBody body = RequestBody.create(JSON, json);
        Request.Builder requestBuilder = new Request.Builder().url(url);
        headers.forEach((k, v) -> requestBuilder.addHeader(k, v));
        Request request = requestBuilder.post(body).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.code() == 200) {
                log.info("http Post 请求成功; [url={}, requestContent={}]", url, json);
                return response.body().string();
            } else {
                log.warn("Http POST 请求失败; [ errorCode = {}, url={}, param={}]", response.code(), url, json);
            }
        } catch (IOException e) {
            throw new RuntimeException("同步http请求失败,url:" + url, e);
        }
        return null;
    }

    /**
    * 描述：提交表单 POST formdata
    * @Title: postDataByForm
    * @param url
    * @param content
    * @param headers
    * @return
    * @author weiyongpeng
    * @date  2024年8月6日 上午8:58:05
     */
    public static String postDataByForm(String url, String content, Map<String, String> headers) {
        MediaType JSON = MediaType.parse(HTTP_FORM);
        @SuppressWarnings("deprecation")
		RequestBody body = RequestBody.create(JSON, content);

        Request.Builder requestBuilder = new Request.Builder().url(url);
        if (headers != null && headers.size() > 0) {
            headers.forEach((k, v) -> requestBuilder.addHeader(k, v));
        }
        Request request = requestBuilder
                .post(body)
                .build();

        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            if (response.code() == 200) {
                log.info("postDataByForm; [postUrl={}, requestContent={}, responseCode={}]", url, content, response.code());
                return response.body().string();
            } else {
                log.warn("Http Post Form请求失败,[url={}, param={}]", url, content);
            }
        } catch (IOException e) {
            log.error("Http Post Form请求失败,[url={}, param={}]", url, content, e);
            throw new RuntimeException("Http Post Form请求失败,url:" + url);
        }
        return null;
    }
    

    //test
    public static void main(String[] args) {
//        String url = "http://www.baidu.com";
    	String url = "http://localhost:8082/rule/rule/model/deploy/listRuleModelByParams";
    	Map<String, String> headers = new HashMap<>();
    	headers.put("Authorization", "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX3R5cGUiOiIwMSIsInVzZXJfaWQiOiJFMEQ5QjlEQkI5QUZDMkZCRTA1MDAyMEEyMDJDMjM4QiIsInVzZXJfbmFtZSI6IjgwMTAwMSIsImlzX2xlc3NvciI6IlkiLCJ1c2VyX2tleSI6ImIyYzE5YzU4LWNhM2EtNDE4ZC04NGZiLWIyZmRlM2EyMDM3ZSIsImVudGVycHJpc2VfaWQiOiIxIiwiZW50ZXJwcmlzZV9uYW1lIjoiYWRtaW5pc3RyYXRvciIsInNvdXJjZV9uYW1lIjoic2xhdmUifQ.AjCX_YkJaf2Ltu8zPHYht3TBwFN8rNRp_HfBMPk3weRm64n7PoN3xOMch7ntY7BT9AO9XANY0fq0UStjjsYgkg");
        System.out.println(httpGet(url,headers));
    }

}
